package com.xh.bussiness.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.xh.bussiness.exam.service.IUserErrorQuestionService;
import com.xh.bussiness.system.bean.dto.StudentBean;
import com.xh.bussiness.system.bean.request.AddStudentResultRecordRequest;
import com.xh.bussiness.system.bean.request.StudentRequest;
import com.xh.bussiness.system.model.Student;
import com.xh.bussiness.system.model.StudentResultRecord;
import com.xh.bussiness.system.service.IStudentResultRecordService;
import com.xh.bussiness.system.service.IStudentService;
import com.xh.bussiness.thirdapi.LongwenApi;
import com.xh.bussiness.tms.model.ClassStudent;
import com.xh.bussiness.tms.service.IClassStudentService;
import com.xh.core.bean.AjaxResult;
import com.xh.core.bean.XhExportHeaderBean;
import com.xh.core.bean.XhPage;
import com.xh.core.constant.AjaxResultConstant;
import com.xh.core.controller.BaseController;
import com.xh.core.util.StringUtils;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Pitt zhang
 * @since 2019-04-09
 */
@Api(tags = "学生相关接口")
@Controller
@RequestMapping("/system/student")
public class StudentController extends BaseController {

    @Autowired
    private IStudentService studentService;
    @Autowired
    private IUserErrorQuestionService userErrorQuestionService;
    @Autowired
    private IStudentResultRecordService studentResultRecordService;
    @Autowired
    private IClassStudentService classStudentService;


    /**
     * 分页数据查询
     * @param page 分页对象
     * @param bean 查询条件Bean
     * @return
     */
    @RequestMapping("/queryByPage")
    @ResponseBody
    public XhPage queryByPage(XhPage page, StudentRequest bean){
        page=studentService.queryStudentPage(page,bean);
        return page;
    }

    /**
     * 导出全部
     * @param bean
     * @return
     */
    @RequestMapping(value="/exportAll",method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult exportAll(StudentRequest bean, HttpServletRequest request) {
        try {
            LinkedHashMap<String,XhExportHeaderBean> exportHeaderBeans=new LinkedHashMap<>();
            //exportHeaderBeans.put("username",new XhExportHeaderBean("用户名"));
            //exportHeaderBeans.put("deleted",new XhExportHeaderBean("是否删除",ImmutableMap.of(0,"否",1,"是")));
            //exportHeaderBeans.put("createTime",new XhExportHeaderBean("创建时间","yyyy-MM-dd HH:mm:ss"));

            String downloadUrl=studentService.exportAll(request,exportHeaderBeans,bean,"queryStudentPage");
            if(downloadUrl!=null){
                return new AjaxResult(AjaxResultConstant.Result.SUCCESS,"",downloadUrl);
            }else{
                return new AjaxResult(AjaxResultConstant.Result.ERROR,"导出失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(AjaxResultConstant.Result.ERROR);
        }
    }

    /**
     * 新增和保存
     * @param studentBean 实体对象
     * @return
     */
    @RequestMapping(value="/saveOrUpdate",method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    public AjaxResult saveOrUpdate(StudentBean studentBean){
        if(studentBean.getId()==null){
            studentService.addStudent(studentBean);
        }else{
            studentService.updateStudent(studentBean);
        }
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS);
    }

    @RequestMapping("/queryById/{id}")
    @ResponseBody
    public AjaxResult queryById(@PathVariable String id){
        Student student = studentService.getById(id);
        if (student == null) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "学生不存在");
        }
        ClassStudent classStudent = new ClassStudent();
        classStudent.setStudentId(id);
        List<ClassStudent> classStudents = classStudentService.getClassStudentDataByStuIdAndClassId(classStudent);
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("student", student);
        retMap.put("classStudents", CollectionUtils.isEmpty(classStudents) ? new ArrayList<>() : classStudents);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, retMap);
    }


    @RequestMapping("/queryByUserId/{userId}")
    @ResponseBody
    public AjaxResult queryByUserId(@PathVariable String userId){
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, studentService.getStudentByUserId(userId));
    }
    /**
     * 删除操作
     * @param id
     * @return
     */
    @RequestMapping("/deleteById")
    @ResponseBody
    @Transactional
    public AjaxResult deleteById(String id){
        studentService.delete(id);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS);
    }

    @RequestMapping("/updateStatus")
    @ResponseBody
    @Transactional
    public AjaxResult updateStatus(Student student){
        studentService.update(student);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS);
    }

    /**
     * 批量删除操作
     * @param ids
     * @return
     */
    @RequestMapping("/batchDelete")
    @ResponseBody
    @Transactional
    public AjaxResult batchDelete(String[] ids){
        studentService.batchDelete(ids);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS);
    }


    @ApiOperation("根据龙文教师id查询学生信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lwTeacherId", value = "龙文教师id", required = true, dataType = "String"),
    })
    @RequestMapping("/queryStudentByLwTeacherId")
    @ResponseBody
    public AjaxResult queryStudentByLwTeacherId(String lwTeacherId) {
        if (StringUtils.isEmpty(lwTeacherId)) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "参数错误");
        }
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, LongwenApi.queryAllStudentByTeacherId(lwTeacherId));
    }


    /**
     * 小程序学生端统计课时、错题数
     * @param lwStudentId
     * @return
     */
    @ApiOperation("小程序学生端统计课时、错题数")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lwStudentId", value = "龙文学生id", required = true, dataType = "String"),
    })
    @RequestMapping("/queryStudentForApplet")
    @ResponseBody
    public AjaxResult queryStudentForApplet(String lwStudentId) {
        if (StringUtils.isEmpty(lwStudentId)) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "参数错误");
        }
        Student student = studentService.queryStudentByLwStudentId(lwStudentId);
        if (student == null) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "学生不存在");
        }
        //已订正数
        Integer totalCorrectCount = userErrorQuestionService.queryCorrectCountByStuId(student.getId(),1);
        //查询剩余课时
        Map<String, Object> map = LongwenApi.queryStudentRemainContractNumber(lwStudentId);
        map.put("TOTALCORRECTCOUNT", totalCorrectCount);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, map);
    }

    /**
     * 查看学生成绩
     * @param lwStudentId
     * @return
     */
    @ApiOperation("查看学生成绩")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lwStudentId", value = "龙文学生id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "contractId", value = "龙文合同id", required = true, dataType = "String"),
    })
    @RequestMapping("/queryStudentResultRecordPage")
    @ResponseBody
    public AjaxResult queryStudentResultRecordPage(XhPage page,String lwStudentId,String contractId) {
        XhPage<StudentResultRecord> studentResultRecordXhPage = studentResultRecordService.queryBylwStudentId(page, lwStudentId,contractId);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS,studentResultRecordXhPage);
    }


    @ApiOperation("添加学生成绩记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "request", value = "学生成绩对象", required = true, dataType = "AddStudentResultRecordRequest"),
    })
    @RequestMapping("/saveOrUpdateStudentResultRecord")
    @ResponseBody
    public AjaxResult saveOrUpdateStudentResultRecord(AddStudentResultRecordRequest request) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, studentResultRecordService.addStudentResultRecord(request));
    }

    @RequestMapping("/studentResultRecord/deleteById/{id}")
    @ResponseBody
    @Transactional
    public AjaxResult deleteStudentResultRecord(@PathVariable String id) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, studentResultRecordService.delete(id));
    }

    @ApiOperation(value = "查询所有学生",notes = "查询所有学生")
    @RequestMapping("/queryAll")
    @ResponseBody
    public AjaxResult queryAll(String classId, String name, Integer groupStatus){
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS,"",studentService.queryByStatus(classId, name, groupStatus));
    }


    @ApiOperation(value = "根据班级查询学生",notes = "根据班级查询学生")
    @GetMapping("/queryStudent")
    @ResponseBody
    public AjaxResult queryStudent(String classId){
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS,"",studentService.queryStudentByClassId(classId));
    }


    @ApiOperation(value = "查询所有学生",notes = "查询所有学生")
    @RequestMapping("/queryByName")
    @ResponseBody
    public AjaxResult queryByName(String name){
        if(StringUtils.isEmpty(name)){
            return new AjaxResult(AjaxResultConstant.Result.SUCCESS,new ArrayList<>());
        }
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS,"",studentService.queryByName(name));
    }
}

